﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace MvcWebScraper.Core
{
	public class LocalFileRepository : ICIDRRepository
	{
		private string _basePath;
		public LocalFileRepository(string basePath)
		{
			_basePath = basePath;
		}

		private string FilePath(Carrier carrier)
		{
			return Path.Combine(_basePath, carrier + ".txt");
		}

		public DateTime? CreateTime(Carrier carrier)
		{
			var path = FilePath(carrier);
			if (!File.Exists(path))
				return null;

			return File.GetCreationTime(path);
		}

		public void Save(Carrier carrier, IList<string> cidr)
		{
			var path = FilePath(carrier);
			File.WriteAllLines(path, cidr.ToArray());
		}

		public CIDR Load(Carrier carrier)
		{
			var path = FilePath(carrier);
			if (!File.Exists(path))
				return null;

			return new CIDR
			       	{
			       		List = File.ReadAllLines(path).ToList(),
			       		CreateDate = File.GetCreationTime(path)
			       	};
		}
	}
}
